import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { Button, Switch, Message, Dialog, Balloon } from '@teamix/ui';
import { Section, YunxiaoIcon } from '@alife/devops-ui';
import { access } from 'components/accessContainer/util';
import { PROJECT_ADMIN_ROLES } from 'utils/constants.js';
import ListLoading from 'atComponents/ListLoading';
import AuthForm from './authForm';
import MirrorTable from './mirrorTable';
import { enterPage } from 'utils/track';
import * as actions from '../actions/index';
import docs from 'utils/docs';
import '../index.scss';
import intl from '../../../../../../../../../locale';

const { pathResource } = window.FORCE;
const { role } = window.FORCE.pathResource;
let timer = null;
class Root extends Component {
  static propTypes = {};

  state = {
    authFormVisible: false,
    disableBtn: true,
    disableSettingSwitch: false,
  };

  componentDidMount() {
    // 组件加载完成后，获取表单项的数据
    const fullName = pathResource.fullName.split('/')[1]
      ? pathResource.fullName.split('/')[1].trim()
      : '';
    document.title = intl.get(
      {
        id: 'code-assets.settingsMirrorSync.containers.root.RepositorySynchronizationFullnameCloudEffect',
        defaultMessage: '仓库同步 · {fullName} · 云效 Codeup',
      },
      { fullName },
    );
    this.props.getMirrorSync();
    this.props.getLastMirrorSyncRecord(
      () => {
        this.setState({
          disableBtn: false,
        });
      },
      () => {
        this.triggerMirrorSyncPolling();
      },
    );

    enterPage('Repo-Settings-data-sync', {
      sendPerf: false,
    });
  }

  componentDidUpdate(prevProps) {
    if (prevProps.settings.enabled !== this.props.settings.enabled) {
      if (this.props.settings.enabled && prevProps.settings.enabled === false) {
        this.triggerMirrorSyncPolling();
      } else {
        timer && clearInterval(timer);
        timer = null;
      }
    }
  }

  componentWillUnmount() {
    timer && clearInterval(timer);
    timer = null;
  }

  triggerMirrorSyncPolling = () => {
    if (!timer) {
      timer = setInterval(() => {
        this.props.getLastMirrorSyncRecord(
          (result) => {
            this.props.updateOverViewData({
              lastMirrorSyncRecord: result,
            });

            this.props.getMirrorSyncList(1);
            this.setState({
              disableBtn: false,
              disableSettingSwitch: false,
            });

            clearInterval(timer);
            timer = null;
          },
          (result) => {
            this.props.updateOverViewData({
              lastMirrorSyncRecord: result,
            });
          },
        );
      }, 2000);
    }
  };

  onSwitch = (checked) => {
    this.props.updateMirrorSync(
      {
        enabled: checked,
      },

      () => {
        this.props.getMirrorSyncSettings();
      },
    );
  };

  showAuthForm = () => {
    this.setState({
      authFormVisible: true,
    });
  };

  unbindMirrorAuthorizedSettings = () => {
    this.props.unbindMirrorAuthorizedSettings((res) => {
      if (res) {
        this.props.getMirrorSync();
        Message.success({
          title: intl.get({
            id: 'code-assets.settingsMirrorSync.containers.root.TheAuthorizationIsRevoked',
            defaultMessage: '解除授权成功',
          }),
          duration: 1500,
        });
      }
    });
  };

  onOkAuthForm = (formData) => {
    this.setState({
      authFormVisible: false,
    });

    this.props.updateMirrorSync(formData, () => {
      Message.success({
        title: intl.get({
          id: 'code-assets.settingsMirrorSync.containers.root.SetSuccessfully',
          defaultMessage: '设置成功',
        }),
        duration: 1500,
      });
    });
  };

  onCancleAuthForm = () => {
    this.setState({
      authFormVisible: false,
    });
  };

  mirrorSync = () => {
    const isAdmin = access(PROJECT_ADMIN_ROLES, role);
    if (isAdmin) {
      const { settings } = this.props;
      const url = settings.mirror_sync_url;
      Dialog.alert({
        messageProps: {
          type: 'warning',
          style: { width: '450px ' },
        },

        title: intl.get({
          id: 'code-assets.settingsMirrorSync.containers.root.Note',
          defaultMessage: '请注意',
        }),
        content: (
          <div style={{ wordBreak: 'break-all' }}>
            <span>
              {intl.get({
                id: 'code-assets.settingsMirrorSync.containers.root.ForcedSynchronizationOverwritesAllGit',
                defaultMessage: '1. 强制同步会覆盖当前仓库和远端仓库不同的所有 Git 改动数据；',
              })}
            </span>
            <br />
            <span>
              {intl.get({
                id: 'code-assets.settingsMirrorSync.containers.root.ToEnsureDataConsistencyData',
                defaultMessage: '2. 为保证数据一致性，同步过程中将暂时禁止仓库写入；',
              })}
            </span>
            <br />
            <span>
              {intl.get({
                id: 'code-assets.settingsMirrorSync.containers.root.TheSynchronizationProcessIsNot',
                defaultMessage: '3. 同步过程不受保护分支、推送规则等规则限制；',
              })}
            </span>
            <br />
            <br />
            <span>
              {intl.get(
                {
                  id: 'code-assets.settingsMirrorSync.containers.root.AreYouSureYouWant',
                  defaultMessage: '确认立即同步 {url} 吗？',
                },
                { url },
              )}
            </span>
          </div>
        ),
        onOk: () => {
          this.props.mirrorSync(
            () => {
              this.setState({
                disableBtn: true,
                disableSettingSwitch: true,
              });

              this.triggerMirrorSyncPolling();
            },
            () => {
              // error handle
              Message.error({
                title: intl.get({
                  id: 'code-assets.settingsMirrorSync.containers.root.UnableToSubmitTheTask',
                  defaultMessage: '任务提交失败，请重试',
                }),
                duration: 2000,
              });
            },
          );
        },
      });
    }
  };

  renderSyncBtn = () => {
    const isAdmin = access(PROJECT_ADMIN_ROLES, role);
    const {
      lastMirrorSyncRecord: { sync_status },
    } = this.props;
    const { disableBtn } = this.state;
    switch (sync_status) {
      case 'SUCCESS':
      case 'FAIL':
        break;
      case 'SYNCHRONIZING':
      case 'READY':
        return (
          <Balloon.Tooltip
            align="tl"
            trigger={
              <Button type="primary" disabled>
                {intl.get({
                  id: 'code-assets.settingsMirrorSync.containers.root.Synchronizing',
                  defaultMessage: '同步中',
                })}
              </Button>
            }
          >
            {intl.get({
              id: 'code-assets.settingsMirrorSync.containers.root.TheRepositoryIsBeingSynchronized',
              defaultMessage: '仓库同步中，暂不支持操作，请稍后再试',
            })}
          </Balloon.Tooltip>
        );

      default:
        break;
    }

    return (
      <Button type="primary" disabled={!isAdmin || disableBtn} onClick={this.mirrorSync}>
        {intl.get({
          id: 'code-assets.settingsMirrorSync.containers.root.SynchronizeNow',
          defaultMessage: '立即同步',
        })}
      </Button>
    );
  };

  render() {
    const { isLoadingSettings, settings } = this.props;
    const url = settings.mirror_sync_url;
    const { account } = settings;
    const { authFormVisible, disableSettingSwitch } = this.state;
    return (
      <>
        <Section
          title={intl.get({
            id: 'code-assets.settingsMirrorSync.containers.root.WarehouseSynchronization',
            defaultMessage: '仓库同步',
          })}
        >
          {!isLoadingSettings ? (
            <div className="mirror-sync-container">
              <div
                className="mirror-sync-container-header"
                style={settings.enabled ? {} : { border: 'none' }}
              >
                <div className="mirror-sync-container-header-text">
                  <div className="mirror-sync-container-header-text-title">
                    {intl.get({
                      id: 'code-assets.settingsMirrorSync.containers.root.EnableVaultSynchronization',
                      defaultMessage: '启用仓库同步',
                    })}
                  </div>
                  <div className="mirror-sync-container-header-text-desc">
                    {intl.get({
                      id: 'code-assets.settingsMirrorSync.containers.root.TheContentOfTheRemote',
                      defaultMessage:
                        '允许强制同步远端仓库内容，请注意，强制同步会覆盖当前仓库和远端来源仓库不同的所有改动',
                    })}

                    <a
                      style={{ marginLeft: 5 }}
                      target="_blank"
                      href={docs('mirror_sync_more')}
                      rel="noreferrer"
                    >
                      {intl.get({
                        id: 'code-assets.settingsMirrorSync.containers.root.LearnMore',
                        defaultMessage: '了解更多',
                      })}
                    </a>
                  </div>
                </div>
                <div className="mirror-sync-container-header-switch">
                  <Switch
                    checked={settings.enabled}
                    onChange={this.onSwitch}
                    disabled={disableSettingSwitch}
                  />
                </div>
              </div>
              {settings.enabled ? (
                <>
                  <AuthForm
                    url={url}
                    visible={authFormVisible}
                    onOk={this.onOkAuthForm}
                    onCancel={this.onCancleAuthForm}
                  />

                  <div className="mirror-sync-container-resource">
                    <Message type="notice">
                      <div className="mirror-sync-container-resource-content">
                        <span style={{ whiteSpace: 'nowrap' }}>
                          <span>
                            {intl.get({
                              id: 'code-assets.settingsMirrorSync.containers.root.ImportSourceRepository',
                              defaultMessage: '导入来源仓库：',
                            })}
                          </span>
                          <Balloon.Tooltip
                            trigger={
                              <span
                                style={{
                                  maxWidth: 470,
                                  overflow: 'hidden',
                                  textOverflow: 'ellipsis',
                                }}
                              >
                                {url}&nbsp;&nbsp;
                              </span>
                            }
                          >
                            {url}
                          </Balloon.Tooltip>
                          <a href={url} target="_blank" rel="noreferrer">
                            <YunxiaoIcon type="share-line" />
                          </a>
                        </span>
                      </div>
                    </Message>
                    <div className="mirror-sync-container-resource-account">
                      <span className="mirror-sync-container-resource-account-info">
                        {intl.get({
                          id: 'code-assets.settingsMirrorSync.containers.root.AuthorizedAccount',
                          defaultMessage: '授权账号：',
                        })}
                        {account ||
                          intl.get({
                            id: 'code-assets.settingsMirrorSync.containers.root.NotSet',
                            defaultMessage: '未设置',
                          })}
                      </span>
                      {account ? (
                        <React.Fragment>
                          <Button
                            type="primary"
                            text
                            onClick={this.showAuthForm}
                            className="mirror-sync-container-resource-account-modify"
                          >
                            {intl.get({
                              id: 'code-assets.settingsMirrorSync.containers.root.ModifyAuthorization',
                              defaultMessage: '修改授权',
                            })}
                          </Button>
                          <Button
                            type="primary"
                            text
                            onClick={this.unbindMirrorAuthorizedSettings}
                            className="mirror-sync-container-resource-account-cancel"
                          >
                            {intl.get({
                              id: 'code-assets.settingsMirrorSync.containers.root.RevokeAuthorization',
                              defaultMessage: '解除授权',
                            })}
                          </Button>
                        </React.Fragment>
                      ) : (
                        <Button
                          type="primary"
                          text
                          onClick={this.showAuthForm}
                          className="mirror-sync-container-resource-account-setnow"
                        >
                          {intl.get({
                            id: 'code-assets.settingsMirrorSync.containers.root.SetNow',
                            defaultMessage: '立即设置',
                          })}
                        </Button>
                      )}
                    </div>
                  </div>

                  <div className="mirror-sync-container-operate">{this.renderSyncBtn()}</div>
                  <MirrorTable {...this.props} />
                </>
              ) : null}
            </div>
          ) : (
            <ListLoading style={{ textAlign: 'center' }} />
          )}
        </Section>
      </>
    );
  }
}

export default connect(
  (state) => state.project.projectSettings.mirror,
  (dispatch) => bindActionCreators(actions, dispatch),
)(Root);
